//
//  FeedsViewController.m
//  iRSSNews
//
//  Created by bk_sport on 12/29/12.
//  Copyright (c) 2012 bk_sport. All rights reserved.
//

#import "FeedsViewController.h"
#import "AddFeedViewController.h"
#import "Feed.h"
#import "AppDelegate.h"
#import "NewsViewController.h"
#import "TDBadgedCell.h"

@interface FeedsViewController ()
@end

@implementation FeedsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"FeedsKey", @"");
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSError *error;
	if (![[self fetchedResultsController] performFetch:&error]) {
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		exit(-1);
	}
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] init];
    self.navigationItem.backBarButtonItem.title = NSLocalizedString(@"BackKey", @"");
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated {
    
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
    
    if(editing) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(buttonAddClick:)];
    }
    else {
        self.navigationItem.leftBarButtonItem = nil;
    }
    
}

- (void)buttonAddClick:(id)sender
{
    AddFeedViewController *addFeed = [[AddFeedViewController alloc] init];
    addFeed.categoryItem = self.cateItem;
    addFeed.isAdd = YES;
    [self.navigationController pushViewController:addFeed animated:YES];
}

#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else return self.fetchedResultsController.fetchedObjects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    TDBadgedCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[TDBadgedCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.badge.radius = 9;
    cell.badge.showShadow = YES;
    
    Feed *item = [self.fetchedResultsController.fetchedObjects objectAtIndex:indexPath.row];
    
    if (indexPath.section == 0) {
        int numberOfNewAll = 0;
        for(int i = 0; i<self.fetchedResultsController.fetchedObjects.count; i++)
        {
            numberOfNewAll += [item.numberOfNewNews intValue];
        }
        
        cell.textLabel.text = NSLocalizedString(@"AllFeedsKey", @"");
        cell.badgeString = [NSString stringWithFormat:@"%i",numberOfNewAll];
    }
    else
    {
        cell.textLabel.text = item.name;
        cell.badgeString = [NSString stringWithFormat:@"%@", item.numberOfNewNews];
    }
    
    return cell;

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return NSLocalizedString(@"FeedsKey", @"");
    }
    return @"";
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 25;
    }
    else return 0;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return UITableViewCellEditingStyleNone;
    }
    else
    {
        self.tableView.allowsSelectionDuringEditing = YES;
        return UITableViewCellEditingStyleDelete;
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        NSManagedObjectContext *context = appDelegate.managedObjectContext;
        
        [context deleteObject:[self.fetchedResultsController.fetchedObjects objectAtIndex:indexPath.row]];
         
        NSError *error = nil;
        if (![context save:&error])
        {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
        
        [tableView reloadData];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Feed *item = self.fetchedResultsController.fetchedObjects[indexPath.row];
    if (tableView.isEditing == 0)
    {
        NewsViewController *newsVC = [[NewsViewController alloc] init];
        newsVC.title = item.name;
        [self.navigationController pushViewController:newsVC animated:YES];
    }
    else
    {
        if (indexPath.section == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iRSSNews" message:NSLocalizedString(@"AlertEditFeedChosenKey", @"") delegate:nil cancelButtonTitle:NSLocalizedString(@"OKKey", @"") otherButtonTitles:nil];
            [alert show];
        }
        else
        {
            AddFeedViewController *addFeed = [[AddFeedViewController alloc] init];
            addFeed.isAdd = NO;
            addFeed.selectedRowFeed = indexPath.row;
            [self.navigationController pushViewController:addFeed animated:YES];
        }
    }
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark - NSFetchedResultsControllerDelegate
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
    switch (type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeDelete:
            [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeMove:
            [self.tableView moveRowAtIndexPath:indexPath toIndexPath:newIndexPath];
            break;
        case NSFetchedResultsChangeUpdate:
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexPath.row inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        default:
            break;
    }
}


#pragma mark - fetchedResultsController

- (NSFetchedResultsController *)fetchedResultsController
{
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    static NSString *EntityName = @"Feed";
    static NSString *CacheName = @"Feed";
    [NSFetchedResultsController deleteCacheWithName:@"Feed"];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:EntityName inManagedObjectContext:appDelegate.managedObjectContext];
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES];
    fetchRequest.entity = entity;
    fetchRequest.sortDescriptors = @[sort];
    fetchRequest.fetchBatchSize = 20;
    
    
    _fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:appDelegate.managedObjectContext sectionNameKeyPath:nil cacheName:CacheName];;
    _fetchedResultsController.delegate = self;
    
    return _fetchedResultsController;
}

@end
